package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.controller.vo.WorkOrderFlowVo;
import com.hunttown.mes.rpc.domain.*;
import com.hunttown.mes.rpc.domain.enums.task.CycleTypeEnum;
import com.hunttown.mes.rpc.domain.enums.task.PriorityTypeEnum;
import com.hunttown.mes.rpc.domain.enums.task.TaskStatusEnum;
import com.hunttown.mes.rpc.domain.query.TransportTaskDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportTaskExecutorDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportTaskReplyDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 任务管理
 * @author: wangjunfu
 * @date: 2020年10月13日 10:36
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/task")
public class TaskController {

    private final static Logger logger = LoggerFactory.getLogger(TaskController.class);

    private final AnalysisManageManageService manageService;
    private final TransportTaskManageService taskService;
    private final TransportUserManageService userService;
    private final TransportTaskExecutorManageService executorService;
    private final TransportTaskReplyManageService replyService;
    private final ModelService modelService;

    @Autowired
    public TaskController(TransportTaskManageService taskService, AnalysisManageManageService manageService, ModelService modelService, TransportUserManageService userService, TransportTaskExecutorManageService executorService, TransportTaskReplyManageService replyService) {
        this.taskService = taskService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.userService = userService;
        this.executorService = executorService;
        this.replyService = replyService;
    }

    //region 数据列表

    /**
     * 发布任务
     *
     * @param request  request
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, TransportTaskDTOQuery dtoQuery) {

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        //查看权限：没有权限则只能查看自己的
        Integer canExec = modelService.getLookAllTaskAuthor(pin);
        if (canExec <= 0) {
            dtoQuery.setUserId(modelService.getUserIdByAdminId(curr_obj.getId()));
        }
        dtoQuery.setTaskType(4); //1年计划/2月计划/3周计划/4日常工作
        dtoQuery.setOrderBy("order by id desc");
        Page<TransportTaskDTO> dataPage = taskService.getForPage(dtoQuery);

        for (TransportTaskDTO item : dataPage.getItems()) {
            item.setUserName(modelService.getUserTrueName(item.getUserId()));
            item.setMainExecutorName(modelService.getUserTrueName(item.getMainExecutor()));
            item.setLimitMinuteName(ConvertUtils.minutesToFormat(item.getLimitMinute()));
            item.setPriorityName(PriorityTypeEnum.getEnumByKey(item.getPriority()));
            item.setCycleName(CycleTypeEnum.getEnumByKey(item.getCycle()));
            item.setStatusName(TaskStatusEnum.getEnumByKey(item.getStatus()));
            item.setCatalogName(modelService.getCatalogName(item.getCatalogId()));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //管理员和司机列表
        modelService.getManageDriverUser(model);

        return "basic/task/index";
    }

    /**
     * 我的任务
     *
     * @param request  request
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = "/mytask", method = RequestMethod.GET)
    public String mytask(HttpServletRequest request, Model model, TransportTaskDTOQuery dtoQuery) {

        //只能查看与自己有关的任务：全体成员、执行者或协作者、抄送者
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        dtoQuery.setExecutor(modelService.getUserIdByAdminId(curr_obj.getId()));
        dtoQuery.setTaskType(4); //1年计划/2月计划/3周计划/4日常工作
        dtoQuery.setOrderBy("order by status asc, id desc");
        Page<TransportTaskDTO> dataPage = taskService.getMytaskForPage(dtoQuery);

        for (TransportTaskDTO item : dataPage.getItems()) {
            item.setUserName(modelService.getUserTrueName(item.getUserId()));
            item.setMainExecutorName(modelService.getUserTrueName(item.getMainExecutor()));
            item.setLimitMinuteName(ConvertUtils.minutesToFormat(item.getLimitMinute()));
            item.setPriorityName(PriorityTypeEnum.getEnumByKey(item.getPriority()));
            item.setCycleName(CycleTypeEnum.getEnumByKey(item.getCycle()));
            item.setStatusName(TaskStatusEnum.getEnumByKey(item.getStatus()));
            item.setCatalogName(modelService.getCatalogName(item.getCatalogId()));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "basic/task/mytask";
    }

    /**
     * 详情
     *
     * @param model model
     * @param id    任务Id
     * @return vm
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(HttpServletRequest request, Model model, Integer id) {
        if (id == null || id <= 0) {
            throw new RuntimeException("未找到任务信息！");
        }

        //判断当前用户是否是主执行者，只有主执行者才有权限接任务
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        Integer userid = modelService.getUserIdByAdminId(curr_obj.getId());

        //region 任务信息
        TransportTaskDTO obj = taskService.getById(id);
        obj.setCatalogName(modelService.getCatalogName(obj.getCatalogId()));
        obj.setUserName(modelService.getUserTrueName(obj.getUserId()));
        obj.setMainExecutorName(modelService.getUserTrueName(obj.getMainExecutor()));
        obj.setLimitMinuteName(ConvertUtils.minutesToFormat(obj.getLimitMinute()));
        obj.setPriorityName(PriorityTypeEnum.getEnumByKey(obj.getPriority()));
        obj.setCycleName(CycleTypeEnum.getEnumByKey(obj.getCycle()));
        obj.setStatusName(TaskStatusEnum.getEnumByKey(obj.getStatus()));

        model.addAttribute("Obj", obj);
        //endregion

        //region 判断是否已阅读
        //主负责人首次进入详情页界面
        if (obj.getStatus() == 0 && obj.getMainExecutor().equals(userid)) {
            TransportTaskDTO update = new TransportTaskDTO();
            update.setId(obj.getId());
            update.setAcceptTime(new Date());
            update.setStatus(1);
            boolean isNext = taskService.updateInfoById(update);
            if (isNext) {
                obj.setStatus(1);
                obj.setAcceptTime(new Date());
            }
        }
        //endregion

        //region 任务跟踪

        //获取当前任务回复列表
        TransportTaskReplyDTOQuery replyQuery = new TransportTaskReplyDTOQuery();
        replyQuery.setTaskId(obj.getId());
        replyQuery.setStopFlag(0);
        replyQuery.setPageSize(50);
        Page<TransportTaskReplyDTO> replyPage = replyService.getForPage(replyQuery);

        TransportUserDTO user;
        for (TransportTaskReplyDTO item : replyPage.getItems()) {
            user = userService.getFromCacheId(item.getExecutor());
            if (user != null) {
                item.setExecutorName(user.getTrueName());
                item.setHeadPicNumber(user.getHeadPicNumber());
            }
        }
        model.addAttribute("replyPage", replyPage);

        if (Objects.equals(userid, obj.getMainExecutor())) {
            model.addAttribute("operateExec", true);
        } else {
            model.addAttribute("operateExec", false);
        }

        //判断当前用户是否是发布人，只有发布人才能结束任务
        if (Objects.equals(obj.getUserId(), userid)) {
            model.addAttribute("completeExec", true);
        } else {
            model.addAttribute("completeExec", false);
        }

        //endregion

        //region 流程进度
        List<WorkOrderFlowVo> flowList = new ArrayList<>();
        WorkOrderFlowVo vo;

        vo = new WorkOrderFlowVo();
        vo.setNodeSort(0);
        vo.setNodeName("新任务");
        vo.setIsActive(1);
        vo.setNodeDescription("");
        flowList.add(vo);

        vo = new WorkOrderFlowVo();
        vo.setNodeSort(1);
        vo.setNodeName("已阅读");
        vo.setIsActive(obj.getStatus() >= 1 ? 1 : 0);
        vo.setNodeDescription(obj.getStatus() >= 1 ? (modelService.getUserTrueName(obj.getMainExecutor()) + " " + obj.getAcceptTimeSr()) : "");
        flowList.add(vo);

        //任务状态：0新任务 1已阅读 2进行中 4已完成 10拒绝 20放弃 30失效 40关闭
        //情形1：0新任务 1已阅读 10拒绝
        if (obj.getStatus() == 10) {
            vo = new WorkOrderFlowVo();
            vo.setNodeSort(10);
            vo.setIsActive(2);
            vo.setNodeName("拒绝");
            vo.setNodeDescription("");
            flowList.add(vo);

        } else {
            //情形2：0新任务 1已阅读 2进行中 4已完成
            vo = new WorkOrderFlowVo();
            vo.setNodeSort(2);
            vo.setNodeName("进行中");
            vo.setIsActive(obj.getStatus() >= 2 ? 1 : 0);
            vo.setNodeDescription(obj.getStatus() >= 2 ? (modelService.getUserTrueName(obj.getMainExecutor()) + " " + obj.getStartTimeSr()) : "");
            flowList.add(vo);

            vo = new WorkOrderFlowVo();
            vo.setNodeSort(4);
            vo.setNodeName("已完成");
            vo.setIsActive(obj.getStatus() >= 4 ? 1 : 0);
            vo.setNodeDescription(obj.getStatus() >= 4 ? (modelService.getUserTrueName(obj.getMainExecutor()) + " " + obj.getEndTimeSr()) : "");
            flowList.add(vo);

            vo = new WorkOrderFlowVo();
            vo.setNodeSort(40);
            vo.setNodeName("关闭");
            vo.setIsActive(obj.getStatus() >= 40 ? 1 : 0);
            vo.setNodeDescription(obj.getStatus() >= 40 ? (modelService.getUserTrueName(obj.getUserId()) + " " + obj.getPublishTimeSr()) : "");
            flowList.add(vo);
        }

        //判断是否逾期
        if (obj.getIsOverdue() == 1) {
            List<WorkOrderFlowVo> newFlowList = new ArrayList<>();

            for (WorkOrderFlowVo item : flowList) {
                newFlowList.add(item);

                //如果环节 == 当前状态，则插入“逾期”状态
                if (item.getNodeSort().equals(obj.getStatus())) {
                    vo = new WorkOrderFlowVo();
                    vo.setNodeSort(item.getNodeSort());
                    vo.setIsActive(2);
                    vo.setNodeName("已逾期");
                    vo.setNodeDescription("");
                    newFlowList.add(vo);
                }
            }

            flowList = newFlowList;
        }

        model.addAttribute("flowList", flowList);
        //endregion

        return "basic/task/detail";
    }

    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return vm
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        TransportTaskDTO obj;

        if (id > 0) {
            obj = taskService.getById(id);
        } else {
            obj = new TransportTaskDTO();
            obj.setId(0);
            obj.setPriority(2);
            obj.setLimitMinute(1440);

            //默认时间是从现在开始1天
            obj.setExpectStartTimeSr(DateConvertUtils.getPastMinutesTime(0));
            obj.setExpectEndTimeSr(DateConvertUtils.getPastMinutesTime(-1440));
        }
        model.addAttribute("Obj", obj);

        //任务分类
        modelService.getCatalogPage(model, 22);

        //优先级
        model.addAttribute("priorityList", PriorityTypeEnum.getEnumList());

        //重复周期
        model.addAttribute("cycleTypeList", CycleTypeEnum.getEnumList());

        //管理员和司机列表
        modelService.getManageDriverUser(model);

        return "basic/task/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportTaskDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            //日期
            objDTO.setExpectStartTime(DateConvertUtils.strToDate(objDTO.getExpectStartTimeSr()));
            objDTO.setExpectEndTime(DateConvertUtils.strToDate(objDTO.getExpectEndTimeSr()));

            //计算开始日期和结束日期相差多少分钟
            objDTO.setLimitMinute(Integer.parseInt(DateUtils.getDistanceMinutes(objDTO.getExpectStartTimeSr(), objDTO.getExpectEndTimeSr()).toString()));

            //如果为空，给个默认值
            if (objDTO.getAllMember() == null) {
                objDTO.setAllMember(0);
            }

            //主执行人不能为空
            if (objDTO.getMainExecutor() == null) {
                map = OperateCode.CompositionResult(map, -10, "请选择主负责人！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            //年月日周
            objDTO.setTaskYear(DateUtils.getDateYear(objDTO.getExpectStartTime()));
            objDTO.setTaskMonth(DateUtils.getDateMonth(objDTO.getExpectStartTime()));
            objDTO.setTaskDay(DateUtils.getDateDay(objDTO.getExpectStartTime()));
            objDTO.setTaskWeek(DateUtils.getDateWeeks(objDTO.getExpectStartTime()));

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setUserId(modelService.getUserIdByAdminId(curr_obj.getId()));    //发布者
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);

                objDTO.setRewardId(0);
                objDTO.setPunishId(0);
                objDTO.setDepId(0);

                //其它默认值
                objDTO.setAcceptTime(DateConvertUtils.strToDate("1990-01-01"));
                objDTO.setStartTime(objDTO.getAcceptTime());
                objDTO.setEndTime(objDTO.getAcceptTime());
                objDTO.setPublishTime(objDTO.getAcceptTime());
                objDTO.setCompleteMinute(0L);
                objDTO.setStatus(0);
                objDTO.setIsDelay(0);
                objDTO.setIsStar(0);

                objDTO.setRealPercent(BigDecimal.ZERO);
                objDTO.setRealCash(0);
                objDTO.setRealScore(0);

                objDTO = taskService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = taskService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region //保存成功后再保存执行者、协作者到中间表
            saveCooperation(objDTO);
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //保存执行者、协作者、抄送者
    private void saveCooperation(TransportTaskDTO objDTO) {

        //region [1].保存执行者
        if (objDTO.getMainExecutor() != null && objDTO.getMainExecutor() > 0) {
            TransportTaskExecutorDTOQuery mainQuery = new TransportTaskExecutorDTOQuery();
            mainQuery.setTaskId(objDTO.getId());
            mainQuery.setPlayerType(1);
            mainQuery.setExecutor(objDTO.getMainExecutor());
            mainQuery.setStopFlag(0);
            mainQuery.setDeleteFlag(0);
            TransportTaskExecutorDTO mainDTO = executorService.getByQuery(mainQuery);

            //删除
            if (mainDTO == null) {
                //物理删除
                executorService.deleteByTaskId(objDTO.getId(), 1);

                //重新插入
                TransportTaskExecutorDTO insert = new TransportTaskExecutorDTO();
                insert.setTaskId(objDTO.getId());
                insert.setPlayerType(1);
                insert.setExecutor(objDTO.getMainExecutor());
                insert.setStopFlag(0);
                insert.setDeleteFlag(0);
                executorService.insert(insert);
            }
        }
        //endregion

        //region [2].保存协作者
        if (StringUtils.isNotBlank(objDTO.getCooperators())) {
            List<String> coopList = FormatUtils.commaToList_String(objDTO.getCooperators());

            //将【协作者】姓名转化为协作者ID
            List<String> UserNameList = new ArrayList<>();
            List<Integer> UserIdList = new ArrayList<>();
            for (String item : coopList) {
                TransportUserDTO userdto = userService.getByTrueName(item.trim());
                if (userdto != null) {
                    UserNameList.add(userdto.getTrueName());
                    UserIdList.add(userdto.getId());
                }
            }

            if (UserIdList.size() > 0) {

                //[STEP.01].取出原协作者
                TransportTaskExecutorDTOQuery oldQuery = new TransportTaskExecutorDTOQuery();
                oldQuery.setTaskId(objDTO.getId());
                oldQuery.setPlayerType(2);
                oldQuery.setStopFlag(0);
                oldQuery.setPageSize(1000);
                Page<TransportTaskExecutorDTO> oldPage = executorService.getForPage(oldQuery);

                //[STEP.02].比较现有协作者
                List<Integer> oldUserIdList = new ArrayList<>();
                List<Integer> delUserIdList = new ArrayList<>();
                List<Integer> addUserIdList = new ArrayList<>();

                //判断新协作者中是否包含旧的，或不包含则是已删除的
                for (TransportTaskExecutorDTO item : oldPage.getItems()) {
                    if (!UserIdList.contains(item.getExecutor())) {
                        delUserIdList.add(item.getId()); //已删除
                    }
                    oldUserIdList.add(item.getExecutor());
                }

                //判断旧协作者是否包含新的，不包含则是新增的
                for (Integer item : UserIdList) {
                    if (!oldUserIdList.contains(item)) {
                        addUserIdList.add(item); //新增
                    }
                }

                //[STEP.03].将删除的协作者删除
                if (delUserIdList.size() > 0) {
                    for (Integer delId : delUserIdList) {
                        //物理删除
                        executorService.deleteByIdForPhysical(delId);
                    }
                }

                //[STEP.04].保存新增的协作者
                TransportTaskExecutorDTO insertdto;
                for (Integer item : addUserIdList) {
                    insertdto = new TransportTaskExecutorDTO();
                    insertdto.setTaskId(objDTO.getId());
                    insertdto.setPlayerType(2);
                    insertdto.setExecutor(item);
                    insertdto.setStopFlag(0);
                    insertdto.setDeleteFlag(0);
                    executorService.insert(insertdto);
                }

                //[STEP.05].如果协作者有差异（比如名字不对），则进行保存
                String newName = StringUtils.join(UserNameList.toArray(), ",");
                if (!objDTO.getCooperators().equals(newName)) {
                    TransportTaskDTO updatedto = new TransportTaskDTO();
                    updatedto.setId(objDTO.getId());
                    updatedto.setCooperators(newName);
                    taskService.updateInfoById(updatedto);
                }
            }
        }
        //endregion

        //region [3].保存抄送者
        if (StringUtils.isNotBlank(objDTO.getCopytors())) {
            List<String> coopList = FormatUtils.commaToList_String(objDTO.getCopytors());

            //将【抄送者】姓名转化为抄送者ID
            List<String> UserNameList = new ArrayList<>();
            List<Integer> UserIdList = new ArrayList<>();
            for (String item : coopList) {
                TransportUserDTO userdto = userService.getByTrueName(item.trim());
                if (userdto != null) {
                    UserNameList.add(userdto.getTrueName());
                    UserIdList.add(userdto.getId());
                }
            }

            if (UserIdList.size() > 0) {

                //[STEP.01].取出原抄送者
                TransportTaskExecutorDTOQuery oldQuery = new TransportTaskExecutorDTOQuery();
                oldQuery.setTaskId(objDTO.getId());
                oldQuery.setPlayerType(3);
                oldQuery.setStopFlag(0);
                oldQuery.setPageSize(1000);
                Page<TransportTaskExecutorDTO> oldPage = executorService.getForPage(oldQuery);

                //[STEP.02].比较现有抄送者
                List<Integer> oldUserIdList = new ArrayList<>();
                List<Integer> delUserIdList = new ArrayList<>();
                List<Integer> addUserIdList = new ArrayList<>();

                //判断新抄送者中是否包含旧的，或不包含则是已删除的
                for (TransportTaskExecutorDTO item : oldPage.getItems()) {
                    if (!UserIdList.contains(item.getExecutor())) {
                        delUserIdList.add(item.getId()); //已删除
                    }
                    oldUserIdList.add(item.getExecutor());
                }

                //判断旧抄送者是否包含新的，不包含则是新增的
                for (Integer item : UserIdList) {
                    if (!oldUserIdList.contains(item)) {
                        addUserIdList.add(item); //新增
                    }
                }

                //[STEP.03].将删除的抄送者删除
                if (delUserIdList.size() > 0) {
                    for (Integer delId : delUserIdList) {
                        //物理删除
                        executorService.deleteByIdForPhysical(delId);
                    }
                }

                //[STEP.04].保存新增的抄送者
                TransportTaskExecutorDTO insertdto;
                for (Integer item : addUserIdList) {
                    insertdto = new TransportTaskExecutorDTO();
                    insertdto.setTaskId(objDTO.getId());
                    insertdto.setPlayerType(3);
                    insertdto.setExecutor(item);
                    insertdto.setStopFlag(0);
                    insertdto.setDeleteFlag(0);
                    executorService.insert(insertdto);
                }

                //[STEP.05].如果抄送者有差异（比如名字不对），则进行保存
                String newName = StringUtils.join(UserNameList.toArray(), ",");
                if (!objDTO.getCopytors().equals(newName)) {
                    TransportTaskDTO updatedto = new TransportTaskDTO();
                    updatedto.setId(objDTO.getId());
                    updatedto.setCopytors(newName);
                    taskService.updateInfoById(updatedto);
                }
            }
        }
        //endregion

    }

    //endregion

    //region 删除

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = taskService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 任务回复

    /**
     * 任务回复
     *
     * @param remark 回复内容
     * @param taskid 任务ID
     * @return vm
     */
    @RequestMapping(value = "/reply", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveReply(HttpServletRequest request, String remark, Integer taskid) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (StringUtils.isBlank(remark) || taskid == null || taskid <= 0) {
            map.put("returnMessage", "请输入回复内容！");
            return map;
        }

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        TransportTaskReplyDTO replyDTO = new TransportTaskReplyDTO();
        replyDTO.setTaskId(taskid);
        replyDTO.setExecutor(modelService.getUserIdByAdminId(curr_obj.getId()));
        replyDTO.setReplyContent(remark);
        replyDTO.setReplyTime(new Date());
        replyDTO.setStopFlag(0);
        replyDTO.setDeleteFlag(0);
        replyDTO = replyService.insert(replyDTO);

        if (replyDTO != null && replyDTO.getId() > 0) {
            map.put("returnCode", 1);
            map.put("returnMessage", "回复成功！");

        } else {
            map.put("returnMessage", "回复失败！");
        }

        return map;
    }

    //endregion

    //region 任务操作

    /**
     * 任务操作
     *
     * @param status 任务状态：0新任务 1已阅读 2进行中 4已完成 10拒绝 20放弃 30失效 40关闭
     * @param taskid 任务ID
     * @return json
     */
    @RequestMapping(value = "/oprateTask", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> oprateTask(HttpServletRequest request, Integer status, Integer taskid) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (status == null || taskid == null || taskid <= 0) {
            map.put("returnMessage", "未查询到任务信息！");
            return map;
        }

        if (status != 1 && status != 2 & status != 10) {
            map.put("returnMessage", "错误的操作类型！");
            return map;
        }

        TransportTaskDTO update = new TransportTaskDTO();
        update.setId(taskid);
        update.setStatus(status);

        //接受任务时间
        if (status == 1) {
            update.setAcceptTime(new Date());
        }

        //开始任务时间
        if (status == 2) {
            update.setStartTime(new Date());
        }

        Boolean isNext = taskService.updateInfoById(update);

        if (isNext) {
            map.put("returnCode", 1);
            map.put("returnMessage", "操作成功！");

        } else {
            map.put("returnMessage", "操作失败！");
        }

        return map;
    }

    //endregion

    //region 任务完成及工作评价

    /**
     * 任务完成及工作评价
     *
     * @param model  model
     * @param taskId 任务ID
     * @param status 任务状态：0新任务 1已阅读 2进行中 4已完成 10拒绝 20放弃 30失效 40关闭
     * @return vm
     */
    @RequestMapping(value = "/taskComplete", method = RequestMethod.POST)
    public String taskComplete(Model model, Integer taskId, Integer status) {
        if (taskId == null || taskId <= 0 || status == null || (status != 4 && status != 40)) {
            return "basic/task/complete-task-modal";
        }

        String showTitle = "任务完成总结";
        String showBtn = "完成任务";

        if (status == 40) {
            showTitle = "工作任务评价";
            showBtn = "工作评价";
        }

        model.addAttribute("showTitle", showTitle);
        model.addAttribute("showBtn", showBtn);
        model.addAttribute("taskId", taskId);
        model.addAttribute("status", status);

        return "basic/task/complete-task-modal";
    }

    @RequestMapping(value = "/saveComplete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveComplete(HttpServletRequest request, Integer taskId, Integer status, String remark) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (taskId == null || taskId <= 0 || status == null || (status != 4 && status != 40)) {
            map.put("returnMessage", "未获取到任务信息！");
            return map;
        }

        if (StringUtils.isBlank(remark)) {
            map.put("returnMessage", "请输入内容！");
            return map;
        }

        TransportTaskDTO taskDTO = new TransportTaskDTO();
        taskDTO.setId(taskId);
        taskDTO.setStatus(status);

        if (status == 4) {
            taskDTO.setCompleteDes(remark);
            taskDTO.setEndTime(new Date());

            TransportTaskDTO origin = taskService.getById(taskId);
            if (origin != null) {
                //完成时长
                String endSr = DateConvertUtils.dateToStr(new Date());
                taskDTO.setCompleteMinute(DateUtils.getDistanceSeconds(origin.getStartTimeSr(), endSr) / 60);

                //是否延期
                if (DateUtils.compareDateTime(origin.getExpectEndTimeSr(), endSr)) {
                    taskDTO.setIsDelay(1);
                }
            }
        }

        if (status == 40) {
            taskDTO.setPublishDes(remark);
            taskDTO.setPublishTime(new Date());
        }

        Boolean isNext = taskService.updateInfoById(taskDTO);

        if (isNext) {
            map.put("returnCode", 1);
            map.put("returnMessage", "操作成功！");
        } else {
            map.put("returnMessage", "操作失败！");
        }


        return map;
    }
    //endregion
}